/**
 * 年月下拉控件
 * @author 孙汉斌 2011-10-24
 *功能说明:
 * 给定初始值initdate,下拉框选择指定年份时则显示指定年至当前年,月份则显示从指定月份开始。选择其他年份时,则显示全部月份
 * 参数说明：
 * 1.initdate: 初始化日期值,格式必须为(YYYY-MM)),为可选项,缺省时或日期格式错误时均默认为当前年月
 * 2.控件name与id均写死为,分别为"year","month"
 */

package com.zjht.gmcc.bean.tag;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;

import com.zjht.gmcc.bean.util.MyFormat;

public class SelectYearMonthTag extends TagSupport {

	private static final long serialVersionUID = 1L;

	private String initdate;


	public SelectYearMonthTag() {
	}

	@SuppressWarnings("static-access")
	public int doStartTag() throws JspException {
		String initdate = this.initdate;
		

//		initdate = MyFormat.formatYearMonth(initdate);// 格式化日期(YYYY-MM),若格式不正确或为空均默认显示当前年月
		

		// 获取initdate的年、月值
		int year = MyFormat.formatInt(initdate.substring(0, 4));
		int month = MyFormat.formatInt(initdate.substring(5, 7));
		//获取当前年份
		int thisyear = MyFormat.getYear();
		
		StringBuilder html = new StringBuilder();

		// 年份下拉框
		html.append("<select name=\"year\" id=\"year\"");
		html.append(" onchange=\"changeYear()\">");
		int i = 0;
		for (i = year; i <= thisyear; i++) {
			html.append("<option value=\"");
			html.append(i);
			html.append("\"");
			if (year == i) {
				html.append(" selected");
			}
			html.append(">");
			html.append(i + "年");
			html.append("</option>");
		}
		html.append("</select>&nbsp;");

		// 月份下拉框
		html.append("<select name=\"month\" ");
		html.append(" id=\"month\" ");
		html.append(">");
		for (i = month; i < 13; i++) {
			html.append("<option value=\"");
			html.append(i);
			html.append("\"");
			if (month == i) {
				html.append(" selected");
			}
			html.append(">");
			html.append(i + "月");
			html.append("</option>");
		}
		html.append("</select>");

		// 年份下拉框onchange触发函数
		html.append("<script language=\"JavaScript\"> ");
		html.append("function changeYear(){\n" );
		html.append("var month=");
		html.append(month);
		html.append(";");
		html.append("var objyear=document.getElementById(\"year\");");
		html.append("var selectyear = objyear.value;");
		html.append("var firstyear=objyear.options[1].value;");
		html.append("var objmonth=document.getElementById(\"month\");objmonth.options.length =1;");
		html.append(" var firstmonth=1;if(selectyear==firstyear){firstmonth=month; }");
		html.append(" for(i=firstmonth;i<13;i++){");
		html.append("objmonth.options.add(new Option( i + \"月\", i))}}");
		html.append("</script>");

		try {
			pageContext.getOut().print(html.toString());
		} catch (Exception e) {
			throw new JspException(e.getMessage());
		}
		html = null;
		return this.SKIP_BODY;
	}

	public String getInitdate() {
		return initdate;
	}

	public void setInitdate(String initdate) {
		this.initdate = initdate;
	}



}
